let util = require('../../utils/util.js')
let reqJs = require('../../utils/req.js')
const QR = require('../../utils/qrcode.js')
const app = getApp()
let cav = null
var imgCache = {}
let file = null

Page({
    data: {
        //180旋转
        imgStatus: false, //是否加载完图片
        slide: 0,
        show_guide_block: true,
        cav: [0, 0],
        now_sequence: 10,
        sequence: 10,
        mapdataUI: [],
        cluesCurrent: -1, //点击选中了哪个

        boxPopupShow: true, //底部弹窗
        // boxPopupShow: false, //底部弹窗
        boxPopupType: 0, //是否是默认弹窗 false为导航



        // 弹窗开关
        popupShow: false, //显示弹窗 测试
        popupType: 0,
        // popupShow: true, //显示弹窗 
        // popupType: 3, //弹窗类型 
        popdata: {}, //传入的弹窗组件的数据

        // 盖章弹窗开关
        ElecSealSmallPopupShow: false, //测试显示弹窗
        ElecSealSmallPopupData: {
            is_use: 0, //是否已盖章
            title: "恭喜获得问卷礼1份",
            verification_code: "", //核销码
        }, //传入的弹窗组件的数据
        // ElecSealSmallPopupShow: true, //显示弹窗
        // ElecSealSmallPopupData: {
        //   is_use: 0, //是否已盖章
        //   title: "MUJI 展示区",
        // //   verification_code: "", //核销码
        // }, //传入的弹窗组件的数据
        reqCheckData: {}, //用户接口
        qtspShow: false,
        getTaskList: [
            // "https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0403/hongqi/z1.png",
            // "https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0403/hongqi/z2.png",
            // "https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0403/hongqi/z3.png",
        ],
        dakaList: [
            "https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0403/hongqi/daka/1.png",
        ],
        selectIndex: 0,
        dakaFlag: false, //是否已打卡
        qtspShow2: false, //

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {


        //动画


        console.log(options)


        let that = this
        console.log('onLoad', app)

        // that.reqClues() // 测试关闭


        let navHieght = wx.getSystemInfoSync().statusBarHeight
        this.setData({
            //获取状态栏高度
            navHieght,
        })

        console.log(options)

        // 扫二维码进入
        if (options.q) {


        } else {

            // 扫太阳码或者跳转进入

        }

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {


    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

        let that = this
        console.log('onshow')
        // 由于关闭小程序 重新打开小程序不会进入app.js下面的回调不会触发，所以重新调用一次。（类似用开发者工具点击刷新）
        // 1154=朋友圈内打开“单页模式” 
        if (wx.getLaunchOptionsSync().scene == 1154) {
            return
        }

        // 不需要openid的接口
        this.getProjectList()

        // 确保 openid 就绪后再执行后续逻辑
        app.globalData.getOpenidPromise
            .then((openid) => {
                // 此处调用需要 openid 的接口
                this.upload()
            })
            .catch((err) => {
                console.error('获取 openid 失败:', err);
            });


    },
    createQrCode: function (url, canvasId, cavW, cavH) {
        //调用插件中的draw方法，绘制二维码图片
        QR.api.draw(url, canvasId, cavW, cavH, this, this.canvasToTempImage);
        // setTimeout(() => { this.canvasToTempImage();},100);
    },
    t_bt2() {
        let text = wx.getStorageSync('openid')

        console.log(text)

        if (text) {
            this.createQrCode(text, "qrcodeCanvas", 250, 250);
            this.setData({
                qrCodeShow: !this.data.qrCodeShow,
            })
        } else {
            wx.showToast({
                title: '网络繁忙',
                icon: "error"
            })
        }

    },
    close() {
        // // 微信小程序定时器
        // setTimeout(() => {
        this.setData({
            qrCodeShow: false
        })
        // }, 500);


    },

    tapChe(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/aiCreationImg/aiCreationImg?id='+id,
        })
    },
    tapChe3(e) {
        let id = e.currentTarget.dataset.id
      
        wx.navigateTo({
            url: '/pages/answers/answers?id='+id,
        })

    },
    tapChe2(e) {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        wx.downloadFile({
            url: 'https://easysart.oss-cn-shenzhen.aliyuncs.com/yang/2023/Toyota/1023/sebg.png',
            success: (res) => {

                this.setData({

                    tempFilePath: res.tempFilePath
                })
                wx.showShareImageMenu({
                    needShowEntrance: false,
                    path: res.tempFilePath,
                    success() {
                        console.log('分享成功');
                    },
                    fail(e) {
                        console.log('分享失败', e);
                    }
                })
            }
        })
        // let selectIndex = e.currentTarget.dataset.index
        // this.setData({
        //     selectIndex,
        // })
        this.setData({

            qtspShow2: true,
        })
    },
    // 点击问卷调查
    surveyTap() {
        wx.showLoading()
        reqJs.questionnaireExchange().then(res => {
            wx.hideLoading()
            console.log('>>>>>', res)
            if (res.data != "") {
                let questionnaireExchangeData = res.data
                this.setData({
                    questionnaireExchangeData,
                })


                let ElecSealSmallPopupData = this.data.ElecSealSmallPopupData

                ElecSealSmallPopupData.is_use = questionnaireExchangeData.is_use
                ElecSealSmallPopupData.verification_code = questionnaireExchangeData.code


                if (questionnaireExchangeData.is_use == 0) {

                    this.setData({
                        ElecSealSmallPopupData,
                        ElecSealSmallPopupShow: true
                    })
                } else {
                    wx.showToast({
                        title: '您已兑换了噢',
                        icon: "error"
                    })
                }


            } else {
                wx.navigateTo({
                    url: '/pages/survey/survey',
                })
            }



        }).catch(error => {
            console.log(error)
        })

    },



    touchmoveComponents(e) {
        if (this.data.show_guide_block) {
            this.setData({
                show_guide_block: false
            })
        }
        console.log("11111111")

    },
    touchendComponents(e) {
        if (!this.data.show_guide_block) {
            this.setData({
                show_guide_block: true
            })
        }
        console.log("222222")

    },

    scan() {
        let that = this

        // 测试：直接id写死
        // let pid = 1
        // that.signIn(did);

        // 正式
        // 扫码获取打卡id 调用打卡接口
        wx.scanCode({
            onlyFromCamera: true,
            success(res) {
                console.log(res)


                if (res.result.indexOf('platform.easys.co') == -1) {
                    wx.showToast({
                        title: '请识别正确的二维码噢',
                        icon: "none"
                    })
                    return
                }


                if (res.result.indexOf('platform.easys.co/hq/more') == -1) {
                    wx.showModal({
                        title: '提示',
                        content: '请用微信扫码',
                        complete: (res) => {
                            if (res.cancel) {

                            }

                            if (res.confirm) {

                            }
                        }
                    })

                    return
                }

                console.log("扫码成功：" + JSON.stringify(res))
                console.log(res)
                let id = util.parameter(res.result, 'id')

                // if (id == 1 || id == 2 || id == 3) {

                that.finishMisson(id)

                // } else {
                //     wx.showToast({
                //         title: '暂无该互动',
                //         icon: "none"
                //     })
                // }


            }
        })

    },
    finishMisson(id) {
        // 更新用户列表数据列表数据
        reqJs.finishMisson(id).then(res => {

            setTimeout(() => {
                wx.showToast({
                    title: '打卡成功',
                })
            }, 500);


            this.getProjectList()



        }).catch(error => {
            console.log(error)
        })
    },
    navigateTo(e) {
        var url = e.currentTarget.dataset.url

        wx.navigateTo({
            url: url,
        })

    },
    // 关弹窗
    boxOnClose() {
        this.setData({
            boxPopupShow: false,
        })

    },



    // 点击打卡点

    // 180旋转
    gts(e) {
        if (!this.data.imgStatus) return
        this.data.slide = e.touches[0].pageX
        player.clear()
    },
    gtm(e) {
        if (!this.data.imgStatus) return
        let ms = e.changedTouches[0].pageX - this.data.slide;
        // this.genGuide(this.data.sequence + Math.floor(ms / 8))
        this.drawGuide(this.data.sequence - Math.floor(ms / 8))
        // console.log('ms', ms)
        this.setData({
            show_guide_block: false
        })
    },
    gte() {
        this.setData({
            sequence: 10,
            now_sequence: 10,
            show_guide_block: true,
            clickStatus: false
        })
        cav.clearRect(0, 0, this.data.cav[0], this.data.cav[1]);


        player.startAnimation();
    },
    drawGuide(pl = 10) {
        pl = pl < 0 ? 0 : pl > 17 ? 17 : pl;
        // pl = pl < 0 ? 0 : pl > 36 ? 36 : pl;
        cav.clearRect(0, 0, this.data.cav[0], this.data.cav[1]);
        cav.drawImage(imgCache, 0, 400 * pl, 600, 400, 0, 0, this.data.cav[0], this.data.cav[1])
        // cav.drawImage(imgCache, 0, 500 * pl, 750, 500, -100, 20, this.data.cav[0] + 200, this.data.cav[1] - 300)
        // cav.drawImage(imgCache, 0, 424 * pl, 1080, 720, -100, 20, this.data.cav[0], this.data.cav[1])
        this.data.now_sequence = pl
    },
    // 180旋转

    imageTap(e) {
        let img = e.currentTarget.dataset.url
        console.log(e)
        wx.previewImage({
            current: img, // 当前显示图片的 http 链接
            urls: [img] // 需要预览的图片 http 链接列表
        })
    },


    toStory() {
        wx.navigateTo({
            url: '/pages/story/story'
        })
    },


    showToast(e) {
        let title = e.currentTarget.dataset.title
        wx.showToast({
            title: title,
            icon: 'none',
        })
    },

    upload() {
        var that = this




        app.getUser().then((res) => {
            console.log(res) //用户信息
            let reqCheckData = res.data
            that.setData({
                reqCheckData,
            })
        })



    },
    getProjectList() {
        // 更新用户列表数据列表数据
        reqJs.getProjectList().then(res => {

            console.log('>>>>>', res)
            console.log('>>>>>', wx.getStorageSync('allPlayProjects'))

            let getTaskList = wx.getStorageSync('allPlayProjects').experience
            
            getTaskList.filter(item => item.id != 36 ),

            this.setData({
                getTaskList
            })


        }).catch(error => {
            console.log(error)
        })
    },
    lastPay() {
        // 更新用户列表数据列表数据
        reqJs.lastPay().then(res => {

            console.log('>>>>>', res)
            let lastPay = res.data
            let use_time = lastPay.use_time
            // 示例用法
            if (use_time) {

                // let use_time2 = util.formatTime(lastPay.use_time);

                // this.setData({
                //   use_time: use_time2,
                // })


                this.setData({
                    use_time,
                })
            }




        }).catch(error => {
            console.log(error)
        })
    },
    // 点击打卡点
    cluesTap(e) {
        var that = this

        let cluesCurrent = e.currentTarget.dataset.index
        let id = e.currentTarget.dataset.id
        this.setData({
            cluesCurrent,
        })
        console.log(cluesCurrent);
        if (this.data.reqCheckData.game_list.indexOf(id) != -1) {
            return
        }

        if (cluesCurrent == 0 || cluesCurrent == 1 || cluesCurrent == 2) {


            wx.navigateTo({
                url: '/pages/ar-exhibits/ar-exhibits?cluesCurrent=' + cluesCurrent
            })

            return
        }
        // else {
        //     this.setData({
        //         popupShow: true, //显示弹窗 
        //         popupType: 1, //弹窗类型 
        //     })
        // }

        if (cluesCurrent == 5) {
            // wx.chooseMedia({
            //     count: 9,
            //     mediaType: ['image'],
            //     sourceType: ['camera'],
            //     maxDuration: 9,
            //     camera: 'back',
            //     success(res) {
            //       console.log(res.tempFiles.tempFilePath)
            //       console.log(res.tempFiles.size)
            //     }
            // })
            this.setData({
                popupShow: true, //显示弹窗 
                popupType: 1, //弹窗类型 
            })
        }












    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        console.log('>>>>>>>>>>>onHide')

    },

    // 获取头像昵称事件
    hideshowCatch() {
        this.setData({
            showUserMsg: false,
            boxPopupShow_u: false,
        })
    },

    // 获取用户头像
    onChooseAvatar(e) {
        let that = this
        // 头像地址要做一次转换
        console.log(e.detail.avatarUrl)
        let userImg = wx
            .getFileSystemManager()
            .readFileSync(e.detail.avatarUrl, 'base64')
        // console.log(userImg)
        const data = {
            // 其他参数
            extend: 'jpg',
            file: userImg,
        }
        wx.showLoading()
        app.$http
            .post(
                'https://chain.artigit.com/file/api/OSSImage/upload',
                data,
                false,
                'json'
            )
            .then((res) => {
                wx.hideLoading()
                if (res.code == 200) {
                    // console.log('>>>>>>>>>>上传成功', res)
                    that.setData({
                        avatarUrl: res.url,
                    })
                } else {
                    console.log('>>>>>>>>>>>>上传失败！')
                    wx.showToast({
                        title: '上传失败!',
                        icon: 'none',
                    })
                }
            })
    },

    getUserInfo() {
        if (this.data.avatarUrl == '' || this.data.avatarNickname == '') {
            wx.showToast({
                title: '填空项不能为空',
                icon: 'none',
            })
            return
        }

        let data = {
            openid: wx.getStorageSync('openid'),
            headimg: this.data.avatarUrl,
            nickname: this.data.avatarNickname,
        }
        wx.showLoading()
        console.log('>>>>>>>>>>>提交的接口数据', data)
        app.$http.post('/Comics/saveUserInfo', data, false, 'json').then((res) => {
            wx.hideLoading()
            if (res.code == 200) {
                console.log('>>>>>>>保存成功!', res)
                wx.showToast({
                    title: '保存成功!',
                    icon: 'none',
                })
                this.setData({
                    isUserFlag: true,
                    showUserMsg: false,
                    boxPopupShow_u: false,
                })
                wx.navigateTo({
                    url: '/packageDZ/pages/passport/passport',
                })
            } else {
                console.log('>>>>>>>>>>保存失败')
            }
        })
    },


    //获取用户手机号码
    getPhoneNumber(e) {
        let that = this
        if (e.detail.code) {
            console.log(e.detail.code, '>>>>>>授权拿到手机号了')
            let data = {
                openid: wx.getStorageSync('openid'),
                code: e.detail.code,
            }
            console.log(data, '>>>>>>>>>>>>>>>获取手机号需要提交的参数')
            wx.hideLoading()
            app.$http.get('/Comics/getPhone', data, false, 'json').then((res) => {
                if (res.code == 200) {
                    wx.showToast({
                        title: '授权成功!',
                        icon: 'none'
                    })
                    this.getsaveUserInfo(res.data)
                } else {
                    wx.showToast({
                        title: '手机号码获取失败！',
                        icon: 'none'
                    })
                }
            })
        } else {
            console.log('获取失败！')
            wx.showToast({
                title: '授权失败！',
                icon: "none"
            })
        }
    },

    // 保存用户手机号
    getsaveUserInfo(phoneNum) {
        let data = {
            openid: wx.getStorageSync('openid'),
            phone: phoneNum,
        }
        app.$http.post('/Comics/saveUserInfo', data, false, 'json').then((res) => {
            if (res.code == 200) {
                console.log('>>>>>>>>>保存成功！')
                wx.navigateTo({
                    url: '/packageDZ/pages/rankGame/rank',
                })
            } else {
                console.log('>>>>>>>>>>保存失败！')
            }
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
        console.log("用户点击右上角分享", e);
        // dialog 是道具的分享
        // let dialog = {}
        // if (e.from === 'button') {
        //   dialog = e.target.dataset.dialog
        // }
        // return {
        //   title: dialog && dialog.name ? dialog.name : '',
        //   path: '/pages/index/index',
        //   imageUrl: dialog && dialog.image ? dialog.image : 'https://easysart.oss-cn-shenzhen.aliyuncs.com/images/Maiden/0925/share.png',
        // }
    },
    // onShareTimeline() {
    //   return {
    //       title: '《雪漫情书》北海道漫画展',
    //       query:'/pages/index/index',   //只是传递参数  不是指定路径
    //       imageUrl: 'https://easysart.oss-cn-shenzhen.aliyuncs.com/images/Maiden/0925/share.png',
    //   }
    // },
})